package com.common.playing.apps.comm.qiniu.ctr;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.common.android.volley.toolbox.RequestListener;
import com.common.android.volley.toolbox.VolleyManager;
import com.common.playing.apps.comm.constans.UrlConstans;
import com.common.playing.apps.comm.qiniu.FormUploadTest;
import com.common.playing.apps.comm.tools.PlayingLog;
import com.common.qiniu.android.http.ResponseInfo;
import com.common.qiniu.android.storage.UpCompletionHandler;
import com.hgk.common.common.qiniu.listener.GetQiniuPicPathsListener;
import com.hgk.common.common.qiniu.model.QiniuToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class GetQiniuToken {
	private static String GET_QINIU_TOKEN_URL= UrlConstans.ZWCOMMOMURL+"/upload/token.json";
	private  String qiniuToken = null;
	private Context mContext;
	private  String mPicPaths = "";
	private  int count=0;
    private  List<QiNiuBean> qiNiuBeanList;
    private  ArrayList<File> fileArrayList;




   static class QiNiuBean{
        String path;
        String key;
    }
	public GetQiniuToken(Context context) {

	}
	public  String getQiniuToken(RequestListener<QiniuToken> requestListener){
		VolleyManager.getInstance().postString(GET_QINIU_TOKEN_URL, null, requestListener, QiniuToken.class);
		return TextUtils.isEmpty(qiniuToken)?null:qiniuToken;
	}
	public  void getQiniuToken(final Context context, final String id,final ArrayList<File> files,final GetQiniuPicPathsListener liPathListener){
		mPicPaths="";
		count=0;
        fileArrayList=files;
		VolleyManager.getInstance().postString(GET_QINIU_TOKEN_URL, null, new RequestListener<QiniuToken>() {

			@Override
			public void requestSuccess(QiniuToken result) {
				String Token = result.getData();
                qiNiuBeanList=new ArrayList<QiNiuBean>();
				if(!TextUtils.isEmpty(Token)){
					FormUploadTest formUploadTest = new FormUploadTest(context, Token);
					for (int i=0;i<files.size();i++){
						final int j=i;
						final File file=files.get(i);
						String fileName = file.getName();
						String path = file.getPath();
						if(path.startsWith("/")){
							if (null != file) {
								try {
									formUploadTest.testFile(file,new UpCompletionHandler() {
										public void complete(String k, ResponseInfo rinfo, JSONObject response) {
											if(rinfo.isOK()){
												PlayingLog.e("hgldebug", "isOK()====" + count);
												String key=null;
												count++;
												file.getPath();
												try {
													key=response.getString("key");
												} catch (JSONException e) {
													e.printStackTrace();
												}
												if(count==files.size()){
													PlayingLog.e("hgldebug", "j==files.size()-1=="+j);
													QiNiuBean qiNiuBean=new QiNiuBean();
													qiNiuBean.key=key;
													qiNiuBean.path=file.getPath();
													qiNiuBeanList.add(qiNiuBean);
													mPicPaths=createKeys(qiNiuBeanList);
													liPathListener.setQiniuPicPath(mPicPaths);
												}else{
													QiNiuBean qiNiuBean=new QiNiuBean();
													qiNiuBean.key=key;
													qiNiuBean.path=file.getPath();
													qiNiuBeanList.add(qiNiuBean);
													PlayingLog.e("hgldebug", "j<files.size()-1=="+j);
												}
											}else{
                                                PlayingLog.i("fyh","not okokokok");
												if(!TextUtils.isEmpty(id)) {
													Intent intent = new Intent();
													intent.setAction("publish_fail");
													intent.putExtra("extra_db_id", id);
													LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
												}
												PlayingLog.e("hgldebug", "isFAIL()===="+count);
											}
										}
									});
								} catch (Throwable e) {
									if(!TextUtils.isEmpty(id)) {
										Intent intent = new Intent();
										intent.setAction("publish_fail");
										intent.putExtra("extra_db_id", id);
										LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
									}
									e.printStackTrace();
									PlayingLog.e("hgldebug", "j<files.size()-1=="+j);
								}
							}
						}else{
							count++;
							if(count==files.size()){
								PlayingLog.e("hgldebug", "j==files.size()-1=="+j);
								QiNiuBean qiNiuBean=new QiNiuBean();
								qiNiuBean.key=file.getPath();
								qiNiuBean.path=file.getPath();
								qiNiuBeanList.add(qiNiuBean);
								mPicPaths=createKeys(qiNiuBeanList);
								liPathListener.setQiniuPicPath(mPicPaths);
							}else{
								QiNiuBean qiNiuBean=new QiNiuBean();
								qiNiuBean.key=file.getPath();
								qiNiuBean.path=file.getPath();
								qiNiuBeanList.add(qiNiuBean);
								PlayingLog.e("hgldebug", "j<files.size()-1=="+j);
							}
						}
					}
				}else{
                    if(!TextUtils.isEmpty(id)) {
                        Intent intent = new Intent();
                        intent.setAction("publish_fail");
                        intent.putExtra("extra_db_id", id);
                        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
                        Toast.makeText(context, result.getMsg(), Toast.LENGTH_SHORT).show();
                    }
				}
			}

			@Override
			public void requestError(com.common.android.volley.VolleyError e) {
                if(!TextUtils.isEmpty(id)) {
                    Intent intent = new Intent();
                    intent.setAction("publish_fail");
                    intent.putExtra("extra_db_id", id);
                    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
                }
				Toast.makeText(context, "你的网络信号跑路了，快把它追回来", Toast.LENGTH_SHORT).show();
			}
		}, QiniuToken.class);
	}

    private  String createKeys(List<QiNiuBean> arrayList){
        String keys = "";
        try {

            for (int i = 0; i < fileArrayList.size(); i++) {
                for (int j = 0; j < arrayList.size(); j++) {
                    if (i == fileArrayList.size() - 1) {
                        if(fileArrayList.get(i).getPath().equals(arrayList.get(j).path)){
                            keys = keys + "/" + arrayList.get(j).key;
                            break;
                        }
                    } else if (fileArrayList.get(i).getPath().equals(arrayList.get(j).path)) {
                        keys=keys+"/"+arrayList.get(j).key+"|";
                        break;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return keys;
    }
}
